package com.clp.inflxudb.core.flux_function;

import com.clp.inflxudb.core.Flux;
import com.clp.inflxudb.core.enums.FluxKey;
import com.clp.inflxudb.core.enums.GroupMode;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;
import lombok.Getter;
import lombok.Setter;
import org.msgpack.core.Preconditions;

import java.util.Arrays;
import java.util.List;

/**
 * 计算总行数，使用getResult()获取查询结果
 */
public class CountSumFluxFunction implements ResultFluxFunction<CountSumFluxFunction, Long> {
    /**
     * 查询后的行数结果
     */
    private Long result;

    @Getter
    @Setter
    private String countKey;

    public CountSumFluxFunction(String countKey) {
        Preconditions.checkArgument(countKey != null, "count key is not null!");
        this.countKey = countKey;
    }

    @Override
    public void doFunction(Flux flux) {
        flux.group(Arrays.asList(FluxKey._measurement), GroupMode.by);
        if (getCountKey() != null) {
            flux.count(getCountKey());
        }

    }

    @Override
    public void afterQuery(List<FluxTable> fluxTableList) {
        if (fluxTableList == null || fluxTableList.isEmpty()) {
            result = 0L;
            return;
        }
        List<FluxRecord> records = fluxTableList.get(0).getRecords();
        result = (Long) records.get(0).getValueByKey(getCountKey());
    }

    @Override
    public Long getResult() {
        return result;
    }

    @Override
    public CountSumFluxFunction reSet() {
        result = 0L;
        return this;
    }
}
